#include "CheckInPanel.h"
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QAction>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QTextEdit>


#include "../../../../../mes/utils/TaskManager.h"
#include "../../../../models/CheckInData.h"
#include "../../../../models/CommonData.h"
#include "../../../../controller/SignalBus.h"
#include "../../../../network/HttpClient.h"

CheckInPanel::CheckInPanel() {
    initComponent();

    client = new HttpClient();
    connect(client,&HttpClient::responseReceived,this,&CheckInPanel::onReciveResponse);
}

void CheckInPanel::initComponent()
{
    const auto layout = new QGridLayout();
    layout->addWidget(initRequestPanel(),0,0,1,1);
    layout->addWidget(initResponsePanel(),1,0,1,1);

    setLayout(layout);
    setTitle(tr("检测进站"));


}

QWidget *CheckInPanel::initRequestPanel()
{
    const auto lbBatch = new QLabel(tr("批次"));
    const auto lineBatch = new QLineEdit();
    const auto lbRequestJson = new QLabel(tr("请求体json"));
    const auto textRequestJson = new QTextEdit();
    const auto btnExecute = new QPushButton(tr("发送请求"));

    const auto batchLine = new QHBoxLayout();
    batchLine->addWidget(lbBatch);
    batchLine->addWidget(lineBatch);

    const auto layout = new QGridLayout();
    layout->addLayout(batchLine,0,0,1,2);
    layout->addWidget(initRequestPcuInfoPanel(),1,0,1,2);
    layout->addWidget(lbRequestJson,2,0,1,1);
    layout->addWidget(textRequestJson,3,0,1,2);
    layout->addWidget(btnExecute,2,1,1,1);

    jsonHash.insert("requestBody",textRequestJson);
    requestVariablesHash.insert("batch",lineBatch);


    connect(btnExecute,&QPushButton::clicked,this,&CheckInPanel::onSendRequest);

    const auto widget = new QWidget();
    widget->setLayout(layout);
    return widget;
}

QWidget *CheckInPanel::initResponsePanel()
{
    const auto lbResultCode = new QLabel(tr("结果代码"));
    const auto lineResultCode = new QLineEdit();

    const auto lbResponseJson = new QLabel(tr("响应体json"));
    const auto textResponseJson = new QTextEdit();

    const auto layout = new QGridLayout();
    layout->addWidget(lbResultCode,0,0,1,1);
    layout->addWidget(lineResultCode,0,1,1,1);
    layout->addWidget(initResponsePcuInfoPanel(),1,0,1,2);
    layout->addWidget(lbResponseJson,2,0,1,2);
    layout->addWidget(textResponseJson,3,0,1,2);

    responseVarialbesHash.insert("resultCode",lineResultCode);
    jsonHash.insert("responseBody",textResponseJson);

    const auto widget = new QWidget();
    widget->setLayout(layout);
    return widget;
}

QWidget *CheckInPanel::initRequestPcuInfoPanel()
{

    const auto lbLocationNo = new QLabel(tr("工位号"));
    const auto lineLocationNo = new QLineEdit();

    const auto lbPcu = new QLabel(tr("SN号"));
    const auto linePcu = new QLineEdit();

    const auto layout = new QGridLayout();

    layout->addWidget(lbLocationNo,0,0,1,1);
    layout->addWidget(lineLocationNo,0,1,1,1);
    layout->addWidget(lbPcu,1,0,1,1);
    layout->addWidget(linePcu,1,1,1,1);

    requestVariablesHash.insert("locationNo",lineLocationNo);
    requestVariablesHash.insert("pcu",linePcu);

    const auto widget = new QWidget();
    widget->setLayout(layout);
    return widget;
}

QWidget *CheckInPanel::initResponsePcuInfoPanel()
{
    const auto lbLocationNo = new QLabel(tr("工位号"));
    const auto lineLocationNo = new QLineEdit();

    const auto lbPcu = new QLabel(tr("SN号"));
    const auto linePcu = new QLineEdit();

    const auto lbResultMsg = new QLabel(tr("返回信息"));
    const auto lineResultMsg = new QLineEdit();

    const auto layout = new QGridLayout();

    layout->addWidget(lbLocationNo,0,0,1,1);
    layout->addWidget(lineLocationNo,0,1,1,1);
    layout->addWidget(lbPcu,1,0,1,1);
    layout->addWidget(linePcu,1,1,1,1);
    layout->addWidget(lbResultMsg,2,0,1,1);
    layout->addWidget(lineResultMsg,3,0,1,2);

    responseVarialbesHash.insert("locationNo",lineLocationNo);
    responseVarialbesHash.insert("pcu",linePcu);
    responseVarialbesHash.insert("resultMsg",lineResultMsg);


    const auto widget = new QWidget();
    widget->setLayout(layout);
    return widget;

}

void CheckInPanel::onSendRequest()
{
    int randomNumber = QRandomGenerator::global()->bounded(10000,100000);
    QString dateTime = QDateTime::currentDateTime().toString("yyyyMMddhhmmssSSS");
    QString transIdStr = QString("%1%2").arg(dateTime).arg(randomNumber);
    QString dateTimeStr = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
    std::string locationNo = requestVariablesHash["locationNo"]->text().toStdString();
    std::string batch = requestVariablesHash["batch"]->text().toStdString();
    std::string pcu = requestVariablesHash["pcu"]->text().toStdString();


    BaseData<CommonData>::execute(&CommonData::setEventTime,dateTimeStr.toStdString());
    BaseData<CommonData>::execute(&CommonData::setTransId,transIdStr.toStdString());
    BaseData<CheckInData>::execute(&CheckInData::setBatch,batch);
    BaseData<CheckInData>::execute(&CheckInData::setLocationNo,locationNo);
    BaseData<CheckInData>::execute(&CheckInData::setPCU,pcu);

    QJsonObject json;
    json["factoryNo"] = QString::fromStdString(BaseData<CommonData>::execute(&CommonData::getFactoryNo));
    json["transId"] = QString::fromStdString(BaseData<CommonData>::execute(&CommonData::getTransId));
    json["eventTime"] = QString::fromStdString(BaseData<CommonData>::execute(&CommonData::getEventTime));
    json["eventUser"] = QString::fromStdString(BaseData<CommonData>::execute(&CommonData::getEventUser));
    json["machineNo"] = QString::fromStdString(BaseData<CommonData>::execute(&CommonData::getMachineNo));
    json["batch"] = QString::fromStdString(batch);

    std::list<CheckInRequestPcuInfo> pcuInfo;
    pcuInfo.push_back({
        locationNo,
        pcu
    });

    BaseData<CheckInData>::execute(&CheckInData::setRequestPcuInfo,pcuInfo);

    QJsonArray pcuInfoArray;
    for(const auto& item:pcuInfo)
    {
        QJsonObject pcuInfoObj;
        pcuInfoObj["locationNo"] = QString::fromStdString(item.locationNo);
        pcuInfoObj["pcu"] = QString::fromStdString(item.pcu);
        pcuInfoArray.append(pcuInfoObj);
    }
    json["pcuInfo"] = pcuInfoArray;

    std::string fullUrl = BaseData<CommonData>::execute(&CommonData::setApiUrl,"/InboundCheckAndData");
    client->PostAysnc(QString::fromStdString(fullUrl),json);

    jsonHash["requestBody"]->setPlainText(QJsonDocument(json).toJson());

    qDebug()<<"[CheckIn] request:"<<json;
    qDebug()<<"[CheckIn] url:" <<fullUrl;
}

void CheckInPanel::onReciveResponse(const QByteArray &json)
{
    qDebug()<<"[CheckIn] response:"<<json;
    QJsonDocument doc = QJsonDocument::fromJson(json);
    if(!doc.isNull())
    {
        QJsonObject obj = doc.object();
        int resultCode = obj["resultCode"].toInt();
        if(resultCode == 0)
        {
            QJsonArray pcuInfoArray = obj["pcuInfo"].toArray();

            if(!pcuInfoArray.isEmpty())
            {
                responseVarialbesHash["locationNo"]->setText(pcuInfoArray.at(0)["locationNo"].toString());
                responseVarialbesHash["pcu"]->setText(pcuInfoArray.at(0)["pcu"].toString());
                responseVarialbesHash["resultMsg"]->setText(pcuInfoArray.at(0)["msg"].toString());
            }
            else
            {
                responseVarialbesHash["resultCode"]->setText(QString::number(resultCode));
                responseVarialbesHash["resultMsg"]->setText(obj["resultMsg"].toString());
            }
        }
        else
        {
            responseVarialbesHash["resultCode"]->setText(QString::number(resultCode));
            responseVarialbesHash["resultMsg"]->setText(obj["resultMsg"].toString());
        }

        jsonHash["responseBody"]->setPlainText(doc.toJson());
    }
}
